import React, { Component } from 'react';
import { Button, Col, DatePicker, Form, Input, message, Modal, Radio, Row, Select, Table,Empty } from 'antd';
import { MinusCircleFilled } from '@ant-design/icons';
import styles from 'src/pages/DataManage/DataArrange/index.module.scss';
import { FormInstance } from 'antd/lib/form';
import { removeNone, removeNonePreview, resetRemoveNone } from 'src/services/DataManage';
import moment from 'moment';

interface Iprops {
    modalVisibleValue:boolean
    modalVisible:any
	FieldData:any
	joinComponentFunc:any
	setOutDataFunc:any
}

class EmptyField extends Component<Iprops,any> {

	formRef = React.createRef<FormInstance>()
	
    state = {
    	visible: false,
    	fieldOrder: [ 0 ],
    	columns: [],
    	dataSource: [],
    	data: [ 'a' ]
    }

    //预览数据
    handlePreview = ( index ) => {
    	const { id,modelId } = this.props.FieldData;
    	let name = `field-${  index}`;
    	let value = this.formRef.current.getFieldValue( name );
    	// let fields = Object.values( value ).filter( value => value );
    	if( value ) {
    		let v = JSON.parse( value )['v'];
    		let rdata = {
    			'componentId': id ,
    			'fields': [ v ],
    			'modelId': modelId
    		};
    		this.previewData( { data: rdata } );
    	}else {
    		message.warning( '请选择字段' );
    	}
    }

    //确认提交
    handleOk = async () => {
    	let f = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    	let a = 'YYYY-MM-DD HH:mm:ss';
    	let b = 'YYYY-MM-DD';
    	this.formRef.current.validateFields().then( async value => {
    		let arrFill = [];
    		let arrClear = [];
    		this.state.fieldOrder.forEach( item => {
    			if( value[`field-${item}`] ) {
    				if( value[`type-${item}`] === 'a' ) {
    					arrClear.push( JSON.parse( value[`field-${item}`] )['v'] );
    				}else {
    					let rv = value[`fill-${item}`];
    					if( value[`t-${item}`]  === 'Date' ) {
    						rv = moment( rv,f ).format( b );
    					}else if( value[`t-${item}`]  === 'DateTime' ) {
    						rv = moment( rv,f ).format( a );
    					}
    					arrFill.push( {
    						name: JSON.parse( value[`field-${item}`] )['v'],
    						value: rv
    					} );
    				}
    			}
    		} );
    		let data = {
    			fillNullFields: arrFill,
    			nonNullFields: arrClear
    		};
    		let info = null;
    		if( this.props.FieldData.edit ) {
    			const { code,name } = this.props.FieldData;
    			info = await resetRemoveNone( { data: { fields: data,componentCode: code,componentName: name,'position': 1 } } );
    		}else {
    			info =  await removeNone( { data: { 'fields': data, 'modelId': this.props.FieldData.modelId, 'position': 1 } } );
    		}
    		if ( info.data.success ) {
    			const data =  info.data.data;
    			let toData = { ...data,
    				form: value,
    				data: this.state.data,
    				edit: this.props.FieldData.edit,
    				fieldOrder: this.state.fieldOrder,
    				nodeType: 'fieldEmpty',
    				style: { 'primaryColor': '#0066FF' },
    				shape: 'SimplicityNode' };
    			this.props.joinComponentFunc( this.props.FieldData,toData,{} );
    			this.handleCancel();
    		}
    	} );
    }

    //取消
    handleCancel = () => {
    	this.props.modalVisible( 'fieldEmptyVisible',false );
    	let data = this.props.FieldData;
    	delete data.edit;
    	this.props.setOutDataFunc( data );
    	this.setState( { fieldOrder: [ 0 ],data: [ 'a' ],visible: false, columns: [], dataSource: [] } );
    	this.formRef.current.resetFields();
    }

    //数据预览
	previewData = async data => {
		const info = await removeNonePreview( data );
		if ( info.data.success ) {
			const { columns,rows } = info.data.data;
			let c = columns.map( item => {return { title: item.desc, dataIndex: item.name, key: item.desc };} );
			this.setState( {
				columns: c,
				dataSource: rows,
				visible: true
			} );
		}
	}

	//删除事件
	handleDel = index => {
		let flist = JSON.parse( JSON.stringify( this.state.fieldOrder ) );
		flist.splice( index,1 );
		this.setState( {
			fieldOrder: flist
		} );
	}
    
	//选择后是否添加下一行选择
	handleSelect = ( item,index,value ) => {
		let a = {};
		a[`t-${item}`] = JSON.parse( value )['t'];  //类型
		const formSelectItem = this.state.fieldOrder;
		let dlist = this.state.data;
		dlist.splice( index,1,'a' );
		let last = formSelectItem[formSelectItem.length - 1];
		if( item === last ) {
			formSelectItem.push( last +1 );
			this.setState( { fieldOrder: formSelectItem,data: dlist } );
		}else {
			a[`type-${item}`] = 'a';
			this.setState( { data: dlist } );
		}
		this.formRef.current.setFieldsValue( { ...a } );
	}
	
	handleChange = ( e,index ) => {
		let dlist = JSON.parse( JSON.stringify( this.state.data ) );
		dlist.splice( index,1,e.target.value );
		this.setState( { data: [ ...dlist ] } );
	}

	componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
		if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.FieldData.form &&this.props.FieldData.edit ) {
			const { form,data,fieldOrder } = this.props.FieldData;
			if( this.props.modalVisibleValue !== prevProps.modalVisibleValue ) {
				let f = form;
				fieldOrder.forEach( item => {
					if( f[`t-${item}`]&&f[`t-${item}`].includes( 'Date' ) ) {
						f[`fill-${item}`] = moment( f[`fill-${item}`] );
					}
				} );
				this.formRef.current.setFieldsValue( f );
				this.setState( { fieldOrder: fieldOrder,
					data: data } );
			}
		}
	}

	// timeChange = ( d,s,item ) => {
	// 	let t = {};
	// 	t[`fill-${item}`] = s;
	// 	this.formRef.current.setFieldsValue( { ...t } );
	// }


	handleRule = ( t,index ) => {
		let data = null;
		if( !t || t=== 'Text' ) return  [ { required: index+1 !== this.state.fieldOrder.length, message: '请填写填充的值' } ];
		switch ( t ) {
			case 'Integer':
				data = { required: true, type: 'integer', message: '请填写数值类型数据，如：12', transform: value => Number( value ) };
				break;
			case 'Float':
				data = { required: true, message: '请填写浮点数类型数据，如12.34', pattern: /^\d*\.\d+$/ };
				break;
			// case 'Text':
			// 	data = { required: true,type: 'any',message: '请填写文本类型数据' };
			// 	break;
			// case 'Date':
			// 	data = { required: true, message: '请填写日期类型数据', pattern: /^[1-2]\d{3}-((0[1-9])|(1[0-2]))-(((0[1-9])|([1-2][0-9])|(3[0-1])))$/ }; //2019-12-04
			// 	break;
			// case 'DateTime':
			// 	data = { required: true, message: '请填写日期时间类型数据',
			// 		pattern: /^[1-2]\d{3}-((0[1-9])|(1[0-2]))-(((0[1-9])|([1-2][0-9])|(3[0-1])))\s(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/ }; //2019-12-04 20:29:20
			// 	break;
		}
		
		// @ts-ignore
		return [ { required: index+1 !== this.state.fieldOrder.length, message: '请填写填充的值' },{ ...data } ];
	}
	
	handleTimeSelect = ( item,index ) => {
		let t = null;
		let d = this.formRef.current.getFieldValue( `field-${item}` );
		if( d ) {
			t = JSON.parse( d )['t'];
		}
		if( t === 'Date' ) {
			return ( 
				<Col span={5}>
					<Form.Item name={`fill-${item}`} rules={[ { required: true, message: '请选择日期' } ]}>
						<DatePicker style={{ width: 240 }}
							placeholder={'请选择日期'} />
					</Form.Item>
				</Col> 
			);
			
		}else if( t === 'DateTime' ) {
			return (
				<Col span={5}>
					<Form.Item name={`fill-${item}`}  rules={[ { required: true, message: '请选择日期时间' } ]}>
						<DatePicker style={{ width: 240 } }
							showTime placeholder={'请选择日期时间'}
							format="YYYY-MM-DD HH:mm:ss" />
					</Form.Item>
				</Col>
			);
		}else {
			return ( 
				<Col span={5}>
					<Form.Item name={`fill-${item}`}
						   rules={this.handleRule( t,index )}>
						<Input style={{ width: 240 }} />
					</Form.Item>
				</Col> 
			);
		}
	}
    
	render() {
		let title = '空值处理';
		if( this.props.FieldData.edit ) {
			title += ' (编辑)';
		}
		return (
    		<Modal title={title}
    			okText={'确定'}
				width={1200}
    			onOk={this.handleOk}
    			onCancel={this.handleCancel }
    			cancelText={'取消'}
				forceRender={true} mask={false} maskClosable={false}
    			visible={this.props.modalVisibleValue}>
    			<Row style={{ marginBottom: '8px' }}><Col span={10}>选择需要排除空值的字段</Col></Row>
    			<Form ref={this.formRef}>
					{
						this.state.fieldOrder.map( ( item,index ) =>
							(
								<Row key={item} gutter={[ 16, 5 ]}>
									<Col span={6}>
										<Form.Item name={`field-${item}`} noStyle={true} rules={ [ { required: index+1 !== this.state.fieldOrder.length, message: '请选择排除空值的字段' } ] } >
											<Select style={{ width: 240 }} onChange={ value => this.handleSelect( item,index,value )}>
												{
													this.props.FieldData.model.fieldMappings.map(
														( i,index ) => (
															// 'i.tempFieldName}'
															<Select.Option key={index} value={JSON.stringify( { v: i.tempFieldName,t: i.finalFieldType } )}>
																{i.finalFieldDesc}
															</Select.Option>
														) )
												}
											</Select>
										</Form.Item>
									</Col>
									<Col span={3}>
										<Form.Item name={`type-${item}`} noStyle={true} initialValue={'a'} >
											<Radio.Group buttonStyle="solid" onChange={e => this.handleChange( e,index )}>
												<Radio.Button value="a">排除</Radio.Button>
												<Radio.Button value="b">填充</Radio.Button>
											</Radio.Group>
										</Form.Item>
									</Col>
									{
										this.state.data[index] === 'b'
											?this.handleTimeSelect( item,index )
											:null
									}
									{
										index+1 !== this.state.fieldOrder.length
											? (
												<Col span={1}>
													<Button
														// style={{ marginLeft: '6px' }}
														type='text'
														// size={'large'}
														onClick={() => this.handleDel( index )}
														icon={<MinusCircleFilled className={ styles.greenBtn } />}>
													</Button>
												</Col>
											)
											:( <Col span={1}/> )
									}
									<Col span={4}
										 className={ styles.greenBtn }
										 style={{ fontSize: '20px' }}
										 onClick={() => this.handlePreview( index )}>
										点击预览空值内容
									</Col>
									<Col span={0}>
										<Form.Item name={`t-${item}`} noStyle={true}>
											<Input/>
										</Form.Item>
									</Col>
								</Row>
							)
						)
					}
    			</Form>
    			{
    				this.state.visible
    					? <Table dataSource={this.state.dataSource}
								 columns={this.state.columns}
								 scroll={{ x: true }}
								 locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}
															 description='选中字段未查询到空值'/> }}
								 pagination={false}/>
    					:null
    			}
    		</Modal>
    	);
	}
}

export default EmptyField;